package com.tron.dobest.java.tronthread;

import java.util.Arrays;
import java.util.List;


/**
 * 使用同步代码块解决线程安全
 */
public class ThreadStart02 {
    public static void main(String[] args) {

        TronThread tronThread = new TronThread();

        Thread thread01 = new Thread(tronThread, "1号窗口");
        Thread thread02 = new Thread(tronThread, "2号窗口");
        Thread thread03 = new Thread(tronThread, "3号窗口");
        Thread thread04 = new Thread(tronThread, "4号窗口");
        Thread thread05 = new Thread(tronThread, "5号窗口");

        List<Thread> threads = Arrays.asList(thread01, thread02, thread03, thread04, thread05);
        threads.forEach(Thread::start);
    }

    public static class TronThread implements Runnable {

        //共享数据出现时，就会出现线程安全问题
        private int ticket = 100;

        @Override
        public void run() {
            while (true) {
                //同步监视器,同步的概念及共享的数据在同一时间只能被一个线程访问，注意同步的位置。从共享数据操作开始。
                synchronized (this) {  //start
                    if (ticket > 0) {
                        System.out.println(Thread.currentThread().getName() + ":卖票，票号：" + ticket);
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        ticket--;
                    } else {
                        break;
                    }
                } //end
            }
        }
    }


}
